import audioSrc from "~/assets/videos/typeword.mp3";

/** 实现打字类 */
export default class Word {
  constructor(word, root, ide) {
    this.name = "wordCoponent";
    this.data = {
      subfix: "|",
      root: "body",
      word: "",
      nowWord: "",
      timer: null,
      ide: 300,
      audioConfig: {
        autoplay: "autoplay",
        type: "audio/mp3",
        loop: "loop",
        src: audioSrc,
        id: `${new Date().getTime()}${Math.random(1, 10).toFixed()}`
      }
    };

    this.setWord(word);
    this.setRoot(root);
    this.setIde(ide);
  }
  run() {
    this.data.timer = setTimeout(() => {
      this.setAudio();
      this.runWord();
    }, 1200);
  }
  setAudio() {
    const audio = document.createElement("AUDIO");
    $(audio).attr(this.data.audioConfig);

    $("body").append(audio);
  }
  isAudioExit() {
    return $(`#${this.data.audioConfig.id}`).length > 0;
  }
  removeAudio() {
    const root = this.data.root;
    const id = this.data.audioConfig.id;
    $(`#${id}`).remove();
  }
  setWord(word) {
    if (!word) {
      throw new Error("必须填写文字");
    }
    this.data.word = word;
  }
  setRoot(root) {
    if (root) {
      this.data.root = root;
    }
  }
  setIde(ide) {
    if (ide) {
      this.data.ide = ide;
    }
  }
  writeWord() {
    const subfix = this.data.subfix;
    const root = this.data.root;
    let nowWord = this.data.nowWord;
    let word = this.data.word;
    const index = nowWord.length;
    nowWord += word[index];
    $(root).html(`${nowWord}${subfix}`);
    this.data.nowWord = nowWord;
    if (index === word.length - 1) {
      this.stopWord();
      this.removeAudio();
    }
  }
  canWirte() {
    return this.data.nowWord.length < this.data.word.length;
  }
  runWord() {
    const ide = this.data.ide;
    this.data.timer = setInterval(() => {
      if (!this.isAudioExit()) this.setAudio();
      if (!this.canWirte()) return;
      this.writeWord();
    }, ide);
  }
  stopWord() {
    const root = this.data.root;
    let word = this.data.word;

    $(root).html(`${word}`);

    this.stop();
  }
  stop() {
    clearInterval(this.data.timer);
  }
  emptyWord() {
    const root = this.data.root;
    const subfix = this.data.subfix;
    this.data.nowWord = "";
    $(root).html(`${subfix}`);
  }
}
